package com.lawyer.uitls;

import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;

public class DateUtils {

	public static Date getTimeByAddMonth(Date date, int count) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		// TODO 暂时改为5分钟
		// cal.add(Calendar.MINUTE, 5);
		cal.add(Calendar.MONTH, count);
		return cal.getTime();
	}

	public static String format(Date date, String type) {
		if (date == null)
			return null;
		SimpleDateFormat df = new SimpleDateFormat(type);
		return df.format(date);
	}

	public static String format(Date date, String type, String temp) {
		if (date == null)
			return temp;
		SimpleDateFormat df = new SimpleDateFormat(type);
		return df.format(date);
	}

	public static String composeUTCTime(Long date) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
		return dateFormat.format(date);
	}

	public static Date composeUTCTime(String dateString) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
		Date date;
		try {
			date = dateFormat.parse(dateString);
		} catch (Exception e) {
			date = null;
		}
		return date;
	}

	public static String composeUTCTime(Date date) {
		if (date == null) {
			return null;
		}
		Long lDate = date.getTime();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

		return dateFormat.format(lDate);
	}

	public static String composeFormatTime(Date date, String format) {
		if (date == null) {
			return null;
		}
		Long lDate = date.getTime();
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);

		return dateFormat.format(lDate);
	}

	public static String composeTime(Date date) {
		if (date == null) {
			return null;
		}
		Long lDate = date.getTime();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		return dateFormat.format(lDate);
	}

	/**
	 * 
	 * date
	 * 
	 * @return Date yyyy-MM-dd
	 */
	public static String composeUTCDate(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date;
		try {
			date = sdf.format(sdf.parse(dateString));
		} catch (Exception e) {
			date = null;
		}
		return date;
	}

	/**
	 * 
	 * date
	 * 
	 * @return Date yyyy-MM-dd
	 */
	public static Date composeStrToDate(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = sdf.parse(dateString);
		} catch (Exception e) {
			date = null;
		}
		return date;
	}

	/**
	 * 
	 * date
	 * 
	 * @return Date yyyy-MM-dd
	 */
	public static Date composeStrToDateTime(String dateString) {
		if (StringUtils.isEmpty(dateString)) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date;
		try {
			date = sdf.parse(dateString);
		} catch (Exception e) {
			date = null;
		}
		return date;
	}

	/**
	 * 
	 * date
	 * 
	 * @return Date yyyy-MM-dd
	 */
	public static String composeDateToString(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dateString;
		try {
			dateString = sdf.format(date);
		} catch (Exception e) {
			dateString = null;
		}
		return dateString;
	}

	/**
	 * 根据用户生日计算年龄
	 */
	public static int getAgeByBirthday(Date birthday) {
		Calendar cal = Calendar.getInstance();

		if (cal.before(birthday)) {
			return 0;
		}

		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

		cal.setTime(birthday);
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

		int age = yearNow - yearBirth;

		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				if (dayOfMonthNow < dayOfMonthBirth) {
					age--;
				}
			} else {
				age--;
			}
		}
		return age;
	}

	/**
	 * 根据用户生日计算年龄
	 */
	public static int getCarByBirthday(Date newDate, Date birthday) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(newDate);
		if (cal.before(birthday)) {
			return 0;
		}
		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

		cal.setTime(birthday);
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

		int age = yearNow - yearBirth;

		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				if (dayOfMonthNow < dayOfMonthBirth) {
					age--;
				}
			} else {
				age--;
			}
		}
		return age;
	}

	public static boolean isValidDate(String str) {
		if (null == str || "".equalsIgnoreCase(str)) {
			return false;
		}
		boolean convertSuccess = true;
		// 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			// 设置lenient为false.
			// 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			convertSuccess = false;
		}
		return convertSuccess;
	}

	public static Date getNextDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_YEAR, 1);
		Date rdate = calendar.getTime();
		return rdate;
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 */
	public static int daysBetween(Date smdate, Date bdate) {

		long between_days = 0;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			smdate = sdf.parse(sdf.format(smdate));
			bdate = sdf.parse(sdf.format(bdate));
			Calendar cal = Calendar.getInstance();
			cal.setTime(smdate);
			long time1 = cal.getTimeInMillis();
			cal.setTime(bdate);
			long time2 = cal.getTimeInMillis();
			between_days = (time2 - time1) / (1000 * 3600 * 24);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return (int) between_days;
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 */
	public static long minutesBetween(Date smdate, Date bdate) {

		long between_minutes = 0;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			smdate = sdf.parse(sdf.format(smdate));
			bdate = sdf.parse(sdf.format(bdate));
			Calendar cal = Calendar.getInstance();
			cal.setTime(smdate);
			long time1 = cal.getTimeInMillis();
			cal.setTime(bdate);
			long time2 = cal.getTimeInMillis();
			between_minutes = (time2 - time1) / (1000 * 60);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return between_minutes;
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * 较小的时间 较大的时间
	 * 
	 * @return 相差分钟
	 */
	public static long getMinutesBetween(long smTime, long bTime) {

		long between_minutes = 0;
		try {
			between_minutes = (bTime - smTime) / (1000 * 60);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return between_minutes < 0 ? 0 : between_minutes;
	}

	/**
	 * 比较两个日期之间的大小
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 */
	public static int compareDay(Date smdate, Date bdate) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			smdate = sdf.parse(sdf.format(smdate));
			bdate = sdf.parse(sdf.format(bdate));
			long result = bdate.getTime() - smdate.getTime();
			if (result > 0)
				return 1;
			if (result == 0)
				return 0;
			if (result < 0)
				return -1;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return -1;
	}

	/**
	 * 比较两个日期之间的大小
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 */
	public static long compareMinute(Date smdate, Date bdate) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");
			smdate = sdf.parse(sdf.format(smdate));
			bdate = sdf.parse(sdf.format(bdate));
			return bdate.getTime() - smdate.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return -1;
	}

	/**
	 *
	 */
	public static int compareOnlyDay(Date dbtime1, Date dbtime2) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date1 = format.parse(format.format(dbtime1));
		Date date2 = format.parse(format.format(dbtime2));
		int a = (int) (Math.abs((date1.getTime() - date2.getTime())) / (1000 * 3600 * 24));
		return a;
	}

	/**
	 * 格式化数字 四舍五入
	 * 
	 * @param value
	 *            数字
	 * @param scale
	 *            保留小数位
	 * @return
	 */
	public static String formatNumber(double value, int scale) {
		NumberFormat nf = NumberFormat.getInstance();
		nf.setRoundingMode(RoundingMode.HALF_UP);// 设置四舍五入
		nf.setMinimumFractionDigits(2);// 设置最小保留几位小数
		nf.setMaximumFractionDigits(2);// 设置最大保留几位小数
		String strHours = nf.format(value);
		return strHours;
	}

	/**
	 * 返回当前日期时间
	 * 
	 * @return
	 */
	public static Date currentDateTime() {
		return new Date(System.currentTimeMillis());
	}

	/**
	 * 获取当前时间之前多少年的时间
	 */
	public static Date getYearsTimeBefore(Integer years) {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.YEAR, -years);
		return c.getTime();
	}

	public static String TIME_TEMPLATE_1 = "%d分钟";

	public static String TIME_TEMPLATE_2 = "%d小时%d分钟";

	public static String getStrTimeBetween(Date smTime, Date bTime) {
		if (smTime == null || bTime == null) {
			return "";
		}
		try {
			long lMinute = getMinutesBetween(smTime.getTime(), bTime.getTime());
			long _lhours = (long) lMinute / 60;
			long _lMinute = lMinute % 60 + 1;
			if (_lhours < 1) {
				return String.format(TIME_TEMPLATE_1, _lMinute);
			} else {
				return String.format(TIME_TEMPLATE_2, _lhours, _lMinute);
			}
		} catch (Exception e) {

		}
		return "";

	}

	public static String BEGIN = "begin";

	public static String END = "end";

	/**
	 * @param date
	 * @param type
	 * @return 计算格式为yyyy-MM-dd时间当天的开始时间和结束时间
	 */
	public static Date getDayBeginOrEndTime(String date, String type) {

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

		try {
			if (BEGIN.equals(type)) {
				return dateFormat.parse(date + " 00:00:00");
			} else if (END.equals(type)) {
				return dateFormat.parse(date + " 23:59:59");
			}
		} catch (ParseException e) {
			return null;
		}
		return null;
	}

	/**
	 * @param date
	 *            需要格式话的时间
	 * @param fomatType
	 *            需要转化的类型yyyy-MM-dd
	 */
	public static String fomateDateString(Date date, String fomatType) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(fomatType);
		return dateFormat.format(date);
	}

	public static List<Date> getAgeLevelDateList(Integer... ageLevelList) {
		List<Date> ageDate = new ArrayList<Date>();
		for (Integer ageLevel : ageLevelList) {
			ageDate.add(getYearsTimeBefore(ageLevel));
		}
		return ageDate;
	}

	// 获取本年的开始时间
	public static java.util.Date getBeginDayOfYear() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, getNowYear());
		// cal.set
		cal.set(Calendar.MONTH, Calendar.JANUARY);
		cal.set(Calendar.DATE, 1);

		return getDayStartTime(cal.getTime());
	}

	// 获取本年的结束时间
	public static java.util.Date getEndDayOfYear() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, getNowYear());
		cal.set(Calendar.MONTH, Calendar.DECEMBER);
		cal.set(Calendar.DATE, 31);
		return getDayEndTime(cal.getTime());
	}

	// 获取某个日期的开始时间
	public static Timestamp getDayStartTime(Date d) {
		Calendar calendar = Calendar.getInstance();
		if (null != d)
			calendar.setTime(d);
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return new Timestamp(calendar.getTimeInMillis());
	}

	// 获取某个日期的结束时间
	public static Timestamp getDayEndTime(Date d) {
		Calendar calendar = Calendar.getInstance();
		if (null != d)
			calendar.setTime(d);
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
		calendar.set(Calendar.MILLISECOND, 999);
		return new Timestamp(calendar.getTimeInMillis());
	}

	// 获取今年是哪一年
	public static Integer getNowYear() {
		Date date = new Date();
		GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
		gc.setTime(date);
		return Integer.valueOf(gc.get(1));
	}

	public static Date addMonth(Date date, int addNum) {
		if (date == null)
			return date;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(calendar.MONTH, addNum);
		return calendar.getTime();
	}

	public static Date setToDayMaxTime(Date date) {
		if (date == null)
			return date;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		calendar.set(Calendar.MILLISECOND, 999);
		return calendar.getTime();
	}

	public static Date setToDayMinTime(Date date) {
		if (date == null)
			return date;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return calendar.getTime();
	}

	public static int getYear(Date date) {
		if (date == null)
			return 0;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.YEAR);
	}

	public static int getMonth(Date date) {
		if (date == null)
			return 0;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);

		return calendar.get(Calendar.MONTH) + 1;
	}

	public static int getDay(Date date) {
		if (date == null)
			return 0;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);

		return calendar.get(Calendar.DAY_OF_MONTH);
	}

	public static String getChnDay(Date date) {
		String strType = "yyyy年MM月dd日";
		SimpleDateFormat df = new SimpleDateFormat(strType);
		return df.format(date);
	}

	public static boolean dateCross(Date leftStartDate, Date leftEndDate, Date rightStartDate, Date rightEndDate) {
		boolean result = ((leftStartDate.getTime() >= rightStartDate.getTime()) && leftStartDate.getTime() < rightEndDate.getTime())
				|| ((leftStartDate.getTime() > rightStartDate.getTime()) && leftStartDate.getTime() <= rightEndDate.getTime())
				|| ((rightStartDate.getTime() >= leftStartDate.getTime()) && rightStartDate.getTime() < leftEndDate.getTime())
				|| ((rightStartDate.getTime() > leftStartDate.getTime()) && rightStartDate.getTime() <= leftEndDate.getTime());
		return result;
	}

	/**
	 * 日期相加减
	 * 
	 * @param time
	 *            时间字符串 yyyy-MM-dd HH:mm:ss
	 * @param num
	 *            加的数，-num就是减去
	 * @return 减去相应的数量的年的日期
	 * @throws ParseException
	 */
	public static Date yearAddNum(Date time, Integer num) {
		// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd
		// HH:mm:ss");
		// Date date = format.parse(time);

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(time);
		calendar.add(Calendar.YEAR, num);
		Date newTime = calendar.getTime();
		return newTime;
	}

	/**
	 * 
	 * @param time
	 *            时间
	 * @param num
	 *            加的数，-num就是减去
	 * @return 减去相应的数量的月份的日期
	 * @throws ParseException
	 *             Date
	 */
	public static Date monthAddNum(Date time, Integer num) {
		// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd
		// HH:mm:ss");
		// Date date = format.parse(time);

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(time);
		calendar.add(Calendar.MONTH, num);
		Date newTime = calendar.getTime();
		return newTime;
	}

	/**
	 * 
	 * @param time
	 *            时间
	 * @param num
	 *            加的数，-num就是减去
	 * @return 减去相应的数量的天的日期
	 * @throws ParseException
	 *             Date
	 */
	public static Date dayAddNum(Date time, Integer num) {
		// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd
		// HH:mm:ss");
		// Date date = format.parse(time);

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(time);
		calendar.add(Calendar.DAY_OF_MONTH, num);
		Date newTime = calendar.getTime();
		return newTime;
	}

	/**
	 * 获取本月第一天时间
	 */
	public static Date getMonthStartDate() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		return calendar.getTime();
	}

	/**
	 * 获取本月最后一天
	 * 
	 */
	public static Date getMonthEndDate() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		return calendar.getTime();
	}

	/**
	 * 获取本周的开始时间
	 */
	public static Date getBeginWeekDate() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
		// 周日是1 ，周一是 2 ，周二是 3
		// 所以，当周的第一天 = 当前日期 - 距离周一过了几天（周一过了0天，周二过了1天， 周日过了6天）
		// 2 - 周一的（dayofweek：2 ）= 0
		// 2 - 周二的（dayofweek：3 ）= -1
		// .
		// .
		// 2 - 周日的（dayofweek：1） = 1（这个是不符合的需要我们修改）===》2 - 周日的（dayofweek：1 ==》8 ）
		// = -6
		if (dayofweek == 1) {
			dayofweek += 7;
		}
		cal.add(Calendar.DATE, 2 - dayofweek);
		return cal.getTime();
	}

	/**
	 * 本周的结束时间 开始时间 + 6天
	 */
	public static Date getEndWeekDate() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
		if (dayofweek == 1) {
			dayofweek += 7;
		}
		cal.add(Calendar.DATE, 8 - dayofweek);// 2 - dayofweek + 6
		return cal.getTime();
	}

	// 生成房间号
	public static String randomNumber() {
		Random random = new Random();
		DecimalFormat df = new DecimalFormat("00");
		String no = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + df.format(random.nextInt(100));
		return no;
	}

	// 生成手机号
	public static String randomPhoneNumber() {
		Random random = new Random();
		DecimalFormat df = new DecimalFormat("00");
		String no = new SimpleDateFormat("HHmmss").format(new Date()) + df.format(random.nextInt(100));

		return "135" + no;
	}

	/**
	 * @param end
	 * @return true=已过期，false=没有过期
	 */
	public static boolean checktime(String end) {

		JSONObject json = getDistanceTime(end);
		long sss = Long.valueOf(json.get("sss").toString());
		System.out.println(sss);

		if (sss > 0) {
			return true;
		}
		return false;
	}

	public static String getTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d = new Date();
		String nowDate = format.format(d);// 获取当前时间
		// System.out.println("获取当前时间= "+ nowDate);
		return nowDate;
	}

	public static JSONObject getDistanceTime(String firstLoginTime) {
		JSONObject dataMap = new JSONObject();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d1;
		String nowTime = df.format(new Date());// 获取当前时间
		// System.out.println("获取当前时间= "+ nowDate);
		try {
			d1 = df.parse(nowTime);
			Date d2 = df.parse(firstLoginTime);// 用户初次登录时间
			long diff = d1.getTime() - d2.getTime();

			dataMap.put("sss", diff);
			return dataMap;
		} catch (ParseException e) {

		}
		return dataMap;

	}
}
